#include "touchrun.h"

#include "../shared/qproject.h"
#include "../shared/qabstractdrive.h"
#include "../shared/qdatamanager.h"
#include "../shared/qglobalobject.h"

#include <QDesktopWidget>
#include <QApplication>
#include <QScriptValue>
#include <QScriptValueIterator>
#include <QVariant>

TouchRun::TouchRun(const QString projectPath):
    QObject(0),
    m_view(NULL),
    m_mainWindow(NULL)
{

    m_dataManager=QDataManager::manager();

    QProject* p=QProject::project();
    int count=p->getRuntimeDataCount();
    for(int i=0;i<count;i++)
    {
        QRuntimeData info=p->getRuntimeData(i);
        m_dataManager->setUserData(info.name(),info.value());
    }
    m_globalObject=QGlobalObject::globalObject();
}

TouchRun::~TouchRun()
{
    if(m_mainWindow!=NULL)
    {
        delete m_mainWindow;

    }
    QGlobalObject::releaseGlobalObject();
    QDataManager::releaseManager();

}

bool TouchRun::exec()
{
    if(QProject::project()->getProjectName()==""
            || QProject::project()->getFirstPage()==""
            || QProject::project()->getRunningSize().isEmpty())
    {
        return false;
    }
    Qt::WindowFlags type=Qt::Window;
    QProject *p=QProject::project();
    if(p->getCouldMax())
    {
        type =type |(Qt::WindowMaximizeButtonHint);
    }
    if(p->getCouldMin())
    {
        type = type | (Qt::WindowMinimizeButtonHint);
    }
    if(!p->getNeedFrame())
    {
        type =type |(Qt::FramelessWindowHint);
    }
    m_mainWindow=new QMainWindow(NULL,type);
    connect(m_mainWindow,SIGNAL(destroyed()),this,SLOT(stop()));
    m_mainWindow->setAttribute(Qt::WA_DeleteOnClose);
    m_view=new QGraphicsView((QWidget*)NULL);
    m_view->setBackgroundBrush(p->getBackColor());
    m_scene=new QGraphicsScene;
    m_view->setScene(m_scene);
    m_view->setFrameStyle(QFrame::NoFrame);
    m_globalObject->setView(m_view);
    m_mainWindow->setCentralWidget(m_view);

    QSize des=QProject::project()->getDesignSize();
    QSize run=QProject::project()->getRunningSize();

    m_mainWindow->resize(run);
    m_view->scale(((qreal)run.width())/des.width(),((qreal)run.height())/des.height());

    m_globalObject->showPage(QProject::project()->getFirstPage());

    QSize sz=QApplication::desktop()->size();
    m_mainWindow->move((sz.width()-m_mainWindow->width())/2,(sz.height()-m_mainWindow->height())/2);
    m_mainWindow->setWindowTitle(QProject::project()->getProjectName());
    m_globalObject->updateGlobal();
    m_mainWindow->show();

    int count=p->getDriveCount();
    for(int i=0;i<count;i++)
    {
        p->getDrive(i).m_drive->start();
    }

    return true;
}

void TouchRun::stop()
{
    m_mainWindow=NULL;
    QProject *p=QProject::project();
    int count=p->getDriveCount();
    for(int i=0;i<count;i++)
    {
        p->getDrive(i).m_drive->stop();
    }
    emit Exit();
}
